package com.yhd.admin.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yhd.admin.bean.SysMenu;
import com.yhd.admin.mapper.SysMenuMapper;

@Service
public class SysMenuServiceImpl implements SysMenuService {
	@Autowired
	private SysMenuMapper sysMenuMapper;
	
	@Override
	public List<SysMenu> getAsyncChildrenByPid(Integer pid) {
		return sysMenuMapper.selectSysMenuByPid(pid);
	}
	
	@Override
	public List<SysMenu> getSyncChildrenByPid(Integer pid) {
		//先查一级
		List<SysMenu> menus = sysMenuMapper.selectSysMenuByPid(pid);
		for(SysMenu menu: menus){
			if(menu.getUrl()==null){
				List<SysMenu> children = getSyncChildrenByPid(menu.getId());
				menu.setChildren(children);
			}
		}
		return menus;
	}
	
	@Override
	public SysMenu checkSysMenuName(SysMenu pmenu) {
		//首先获取子菜单
		List<SysMenu> menus = sysMenuMapper.selectSysMenuByPid(pmenu.getPid());
		for(SysMenu menu: menus){
			//检查名字是否存在
			if(menu.getName().equals(pmenu.getName())){
				return menu;
			}
		}
		return null;
	}

	@Override
	public int addSysMenu(SysMenu menu) {
		return sysMenuMapper.insertSysMenu(menu);
	}

	@Override
	public SysMenu getMenuById(int id) {
		return sysMenuMapper.selectSysMenuById(id);
	}

	@Override
	public int updateSysMenu(SysMenu menu) {
		return sysMenuMapper.updateSysMenu(menu);
	}

	//递归删除菜单
	@Override
	public void deleteSysMenuById(int id) {
		//查找子菜单
		List<SysMenu> sons = sysMenuMapper.selectSysMenuByPid(id);
		//如果有就删除子菜单
		if(sons!=null && sons.size()>0){
			for(SysMenu m: sons){
				deleteSysMenuById(m.getId());
			}
		}
		sysMenuMapper.deleteSysMenuById(id);
	}

}
